package net.Stratus.ImageDumper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Logger {
	
	private static ArrayList<Integer> jobIDs = new ArrayList<Integer>();
	private static ArrayList<Integer> windows = new ArrayList<Integer>();
	private static ArrayList<String> logs = new ArrayList<String>();
	
	/**
	 * Creates a new logger
	 * 
	 * @param id job id 
	 */
	public static void newLogger(int id) {
		jobIDs.add(new Integer(id));
		logs.add("");
		
		// make sure there's a log folder;
		new File("logs\\").mkdirs();
		// create log file
		File log = new File("logs\\"+id+".log");
		try {
			log.createNewFile();
		} catch (IOException e) {
		}
	}
	
	public static void newWindow(Integer id) {
		windows.add(id);
	}
	
	public static void removeWindow(Integer id) {
		windows.remove(id);
	}
	
	/**
	 * Logs a message to a particular window and adds \r\n
	 * 
	 * @param id job id 
	 * @param message message to log
	 */
	public static void logln(int id, String message) {
		log(id, message+"\r\n");
	}
	
	/**
	 * Logs a message to a particular window
	 * 
	 * @param id job id 
	 * @param message message to log
	 */
	public static void log(int id, String message) {
		int index = -1;	
		for(int i = 0; i < jobIDs.size(); i++) {
			if(jobIDs.get(i).intValue() == id) {
				index = i;
				break;
			}
		}
		if(index != -1) {
			// add to new string arraylist if there's an open window
			for(int i = 0; i < windows.size(); i++) {
				if(windows.get(i).intValue() == id) {
					logs.set(index, logs.get(index)+message);
					break;
				}
			}
			
			// add to log file
			File log = new File("logs\\"+id+".log");
			if(log.exists() && log.canWrite()) {
				try {
					FileWriter fstream = new FileWriter(log, true);
					BufferedWriter out = new BufferedWriter(fstream);
					out.append(message);
					out.flush();
					out.close();
					fstream.flush();
					fstream.close();
				} catch (IOException e) {
					
				}
			}
		}
	}
	
	public static String getLog(int id) {
		int index = -1;	
		for(int i = 0; i < jobIDs.size(); i++) {
			if(jobIDs.get(i).intValue() == id) {
				index = i;
				break;
			}
		}
		if(index != -1) {
			String ret = logs.get(index);
			logs.set(index, "");
			return ret;
		} else return "";
	}
	
	public static String getLogFile(int id) {
		File log = new File("logs\\"+id+".log");
		if(log.exists() & log.canRead()) {
			return IOHelper.fileToString(log);
		} else return "";
	}
}
